<template>
  <el-dialog :title="title"
             :visible.sync="visible"
             width="40%"
             :before-close="modalClose">
    <el-form ref="formDataRef"
             :model="formData"
             label-width="120px"
             :rules="formDataRules">
      <el-form-item label="医联体名称："
                    prop="name">
        <el-input v-model="formData.name"
                  placeholder="请输入医联体名称"
                  clearable
                  @change="queryName"
                  class="w-200"></el-input>
      </el-form-item>
      <el-form-item label="头部医院："
                    prop="leaderHospitalId">
        <el-select v-model="formData.leaderHospitalId"
                   filterable
                   remote
                   reserve-keyword
                   placeholder="请输入头部医院"
                   :remote-method="querySearchAsync"
                   :loading="loading1"
                   @change="handleSelect"
                   class="w-200">
          <el-option v-for="item in options1"
                     :key="item.hospitalId"
                     :label="item.name"
                     :value="item.hospitalId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="医联体单位："
                    prop="hospitalDtoList">
        <el-select v-model="formData.unionHospitalIds"
                   multiple
                   filterable
                   remote
                   reserve-keyword
                   placeholder="请输入医联体单位"
                   :remote-method="searchMethod"
                   :loading="loading"
                   @change="handleSelectUnion"
                   class="w-200">
          <el-option v-for="item in options"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
        <el-button type="primary"
                   @click="handleAdd(formData.unionHospitalIds)">新 增
        </el-button>
      </el-form-item>
      <el-form-item label="已选医院"
                    prop="hospitalDtoList">
        <el-table :data="formData.hospitalDtoList"
                  border
                  class="mt-20"
                  style="width: 100%">
          <el-table-column prop="name"
                           label="已选医院">
          </el-table-column>
          <el-table-column prop="address"
                           label="地址">
          </el-table-column>
          <el-table-column prop="option"
                           label="操作"
                           width="100">
            <template slot-scope="scope">
              <el-button type="danger"
                         @click="delTable(formData.hospitalDtoList, scope.$index)">删 除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>

    <span slot="footer">
      <el-button @click="modalClose">取 消</el-button>
      <el-button type="primary"
                 @click="submitForm">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
export default {
  props: {
    dataObj: {
      type: Object,
      default: {}
    },
    visible: {
      type: Boolean,
      default: false
    },
    getList: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      loading: false,
      loading1: false,
      title: '新 增',
      pageIndex: 1,
      pageSize: 20,
      formData: {
        id: null,
        name: '', // 医联体名称
        leaderHospitalId: '', // 头部医院ID
        unionHospitalIds: '', // 医联体单位ids字符串
        hospitalDtoList: [],
      },
      formDataRules: {
        name: [{required: true, message: '请输入医联体名称', trigger: 'blur'}],
        leaderHospitalId: [{required: true, message: '请输入头部医院', trigger: 'blur'}],
        hospitalDtoList: [{required: true, message: '请配置医联体', trigger: 'blur'}]
      },
      restaurants: [],
      topicList: [],
      topicList1: [],
      options: [],
      options1: [],
    }
  },
  methods: {
    modalClose() {
      this.$emit('update:visible', false); // 直接修改父组件的属性
    },
    // 查询医联体名字是否重复
    queryName() {
      this.post(this.api.medicalConsortium.getDuplicateName, {
        id: null,
        name: this.formData.name
      }).then(res => {
        if (res.data.code === '200') {
        }
      })
    },

    // 查询头部医院
    querySearchAsync(query) {
      if (query !== '') {
        let _this = this;
        _this.loading1 = true;
        this.post(this.api.medicalConsortium.getHospitalList, {
          pageIndex: this.pageIndex - 1,
          pageSize: this.pageSize,
          searchCondition: query
        }).then(res => {
          if (res.data.code === '200') {
            _this.loading1 = false;
            _this.topicList1 = res.data.object;
          }
        })

        /**
         * 搜索内容渲染到下拉框
         * 从 this.topicList1 把数据赋值到 this.options1
         * 只有这样才能起作用
         */
        setTimeout(() => {
          _this.loading1 = false;
          _this.options1 = _this.topicList1.filter(item => item.name.indexOf(query) > -1);
        }, 200);
      } else {
        this.options1 = [];
      }
    },
    // 选择头部医院
    handleSelect(item) {
      this.formData.leaderHospitalId = item;
    },
    // 搜索医联体单位
    searchMethod(query) {
      if (query !== '') {
        let _this = this;
        _this.loading = true; // 锁住
        this.post(this.api.medicalConsortium.getHospitalPage, {
          pageIndex: this.pageIndex - 1,
          pageSize: this.pageSize,
          name: query
        }).then(res => {
          if (res.data.code === '200') {
            _this.loading = false;
            _this.topicList = res.data.object;
          }
        })

        /**
         * 搜索内容渲染到下拉框
         * 从 this.topicList 把数据赋值到 this.options
         * 只有这样才能起作用
         */
        setTimeout(() => {
          _this.loading = false;
          _this.options = _this.topicList.filter(item => item.name.indexOf(query) > -1);
        }, 200);
      } else {
        this.options = [];
      }
    },
    // 选中医联体单位
    handleSelectUnion(item) {
      this.formData.unionHospitalIds = item;
    },
    handleAdd(params) {
      if (params.length === 0) {
        this.$message.warning('请选择医联体单位!');
        return
      }
      // 第一种方法 try...catch 结束forEach循环
      /* try {
        this.formData.hospitalDtoList.forEach(item => params.some(ele => {
          if (item.id === ele) {
            this.$message.warning('不能重复添加医联体单位!');
            this.formData.unionHospitalIds = [];
            throw new Error('e');
          }
        }))
        let temp = this.topicList.filter(item => params.some(ele => ele === item.id));
        this.formData.hospitalDtoList = [...this.formData.hospitalDtoList, ...temp];
        this.formData.unionHospitalIds = [];
      } catch (e) {
        if (e.message !== 'e') { throw e }
      } */
      // 第二种方法
      if (this.formData.hospitalDtoList.some(item => params.includes(item.id))) {
        this.$message.warning('不能重复添加医联体单位!');
        this.formData.unionHospitalIds = [];
        return
      }
      // 当新增1条数据的时候，可以直接push
      /*  let obj = this.topicList.find(item => params.includes(item.id));
       this.formData.hospitalDtoList.push(obj);
       this.formData.unionHospitalIds = []; */
      // 当新增多条数据的时候，需要合并数组
      let temp = this.topicList.filter(item => params.some(ele => ele === item.id));
      this.formData.hospitalDtoList = [...this.formData.hospitalDtoList, ...temp];
      this.formData.unionHospitalIds = [];
    },
    // 提交
    submitForm() {
      this.$refs.formDataRef.validate(async (valid) => {
        if (valid) {
          let unionHospitalIds = this.formData.hospitalDtoList.map(item => item.id);
          let params = {
            ...this.formData,
            unionHospitalIds: JSON.stringify(unionHospitalIds)
          }
          const {data: res} = await this.post(this.api.medicalConsortium.saveMedicalUnion, params)
          if (res.code === '200') {
            this.$message.success('保存成功!');
            this.modalClose();
            this.$parent.getList();
          }
        }
      });
    },
    // 获取详情
    async getDetail() {
      const {data: res} = await this.post(this.api.medicalConsortium.getMedicalUnionDetail, {
        id: this.dataObj.id
      });
      if (res.code === '200') {
        let resData = res.object;
        this.formData.id = resData.id;
        this.formData.name = resData.name;
        this.formData.hospitalDtoList = resData.hospitalDtoList;
        // 回显头部医院
        this.formData.leaderHospitalId = resData.leaderHospitalId;
        this.options1 = [{
          hospitalId: resData.leaderHospitalId,
          name: resData.hospitalName,
        }]
      }
    },
    delTable(table, index) {
      if (this.dataObj) {
        //编辑
        this.removeMedicalUnionHospital(table[index].id, index)
      } else {
        table.splice(index, 1);
      }

    },
    removeMedicalUnionHospital(hospitalId, index) {
      this.post(this.api.medicalConsortium.removeMedicalUnionHospital, {
        healthCheckMedicalUnionId: this.dataObj.id,
        hospitalId: hospitalId
      }).then((res) => {
        if (res.data.code === '200') {
          this.formData.hospitalDtoList.splice(index, 1)
        } else {
          this.$message.warning(res.data.message)
        }
      })
    },
  },
  created() {
    if (this.dataObj) {
      this.title = '编 辑';
      this.getDetail();
    } else {
      this.title = '新 增';
    }
  }
}
</script>
<style scoped lang="scss">
</style>
